package com.eascs.fp.message.server.impl;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.fp.common.constants.SendType;
import com.eascs.fp.common.dto.MessageDTO;
import com.eascs.fp.common.dto.MessageReceiver;
import com.eascs.fp.common.entity.MsgSmsEntity;
import com.eascs.fp.common.entity.MsgTemplateEntity;
import com.eascs.fp.common.vo.ModelResult;
import com.eascs.fp.common.vo.MsgSmsQueryVO;
import com.eascs.fp.message.IMessageService;
import com.eascs.fp.message.IMsgSmsService;
import com.eascs.fp.message.manager.IMsgSmsManager;
import com.eascs.fp.message.manager.IMsgTemplateManager;
import com.eascs.fp.message.util.HttpUtil;

@Service
public class MsgSmsServiceImpl implements IMsgSmsService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Inject
	IMsgSmsManager msgSmsManager;
	
	@Inject
	IMsgTemplateManager templateManager;
	
	@Inject
	IMessageService messageService;
	
	
	@Value("${msg.emay.sendsms.url}")
	private String sendMessageUrl;
	@Value("${msg.emay.cdkey}")
	private String emayCdkey;
	@Value("${msg.emay.password}")
	private String emayPassword;
	@Value("${msg.message.sendername}")
	private String sendername;
	

	@Override
	public ModelResult<Boolean> sendAuthCode(String templateCode, String phone) {
		ModelResult<Boolean> result = new ModelResult<Boolean>();
		MsgTemplateEntity template = templateManager.queryByCode(templateCode);
		if(template == null){
			result.withError("Server_Msg_Sms_Error_Limit", "短信模板未找到，请配置短信模板");
			logger.info("给用户[{}]发送验证码失败，短信模板未找到[{}]", phone, templateCode);
			return result;
		}
		
		int times = template.getTimesPerHour();
		int counts = msgSmsManager.countPerHour(phone);
		if(counts >= times){
			result.withError("Server_Msg_Sms_Error_Limit", "发送的验证码超过模板的小时次数限制");
			logger.info("给用户[{}]发送验证码失败，超过模板[{}],小时限制数[{}]次,已发送[{}]", phone, templateCode, times, counts);
			return result;
		}
		
		times = template.getTimesPerDay();
		counts = msgSmsManager.countPerDay(phone);
		if(counts >= times){
			result.withError("Server_Msg_Sms_Error_Limit", "发送的验证码超过模板的天次数限制");
			logger.info("给用户[{}]发送验证码失败，超过模板[{}],每天限制数[{}]次,已发送[{}]", phone, templateCode, times, counts);
			return result;
		}
		
		String authCode = RandomStringUtils.randomNumeric(6);
		
		MsgSmsEntity sms = new MsgSmsEntity();
		sms.setCreateTime(new Date());
		sms.setPhoneReceiver(phone);
		sms.setSmsStatus((byte)0);
		sms.setSmsType((byte)0);
		sms.setTemplateCode(templateCode);
		sms.setSmsContent(authCode);
		
		String content = MessageFormat.format(template.getTemplateContent(), authCode);
		
		logger.info("准备发送验证码,用户:[{}],验证码:[{}]", phone, authCode);
		// 发送 GET 请求
		Map<String, String> param=new HashMap<>();
		param.put("cdkey", emayCdkey);
		param.put("password", emayPassword);
		param.put("phone", phone);
		param.put("message", content);
		String smsXml=HttpUtil.sendGet(sendMessageUrl,param);
		ModelResult<Boolean> smsSucc =HttpUtil.convertXml(smsXml);
		if(smsSucc.isSuccess() && smsSucc.getModel()){
			boolean succ = msgSmsManager.add(sms);
			if(succ){
				result.withModel(succ);
				logger.info("给用户[{}]发送验证码[{}]成功", phone, authCode);
			} else{
				result.withError("Server_Msg_Sms_Error_Send", "保存短消息失败");
			}
		}else{
			result.withError("Server_Msg_Sms_Error_Send", "发送短消息失败,原因:" + smsSucc.getErrMsg());
			logger.info("给用户[{}]发送验证码失败，原因：[{}]", phone, smsSucc.getErrMsg());
		}
		
		return result;
	}
	
	@Override
	public ModelResult<Boolean> sendSms(String templateCode, byte msgType, String phone, Object[] params) {
		MsgTemplateEntity template = templateManager.queryByCode(templateCode);
		
		ModelResult<Boolean> result = new ModelResult<Boolean>();
		MsgSmsEntity sms = new MsgSmsEntity();
		sms.setCreateTime(new Date());
		sms.setPhoneReceiver(phone);
		sms.setSmsStatus((byte)1);
		sms.setSmsType(msgType);
		sms.setTemplateCode(templateCode);
		
		String content = MessageFormat.format(template.getTemplateContent(), params);
		if(msgType == 0){
			sms.setSmsContent(content);
		} else{
			sms.setSmsContent(content);
		}
		
		MessageDTO msg = new MessageDTO();
		msg.setMsgContent(content);
		msg.setSenderName(sendername);
		msg.setSendType(SendType.NOW);
		
		List<MessageReceiver> receivers = new ArrayList<MessageReceiver>();
		MessageReceiver receiver = new MessageReceiver();
		receiver.setName("金融平台客户");
		receiver.setPhone(phone);
		receivers.add(receiver);
		msg.setReceivers(receivers);
		
		ModelResult<Boolean> smsSucc = messageService.sendMsg(msg);
		
		if(smsSucc.isSuccess() && smsSucc.getModel()){
			
			boolean succ = msgSmsManager.add(sms);
			if(succ){
				result.withModel(succ);
				logger.info("给用户[{}]发送短消息[{}]成功", phone, content);
			} else{
				result.withError("Server_Msg_Sms_Error_Send", "保存短消息失败");
			}
		} else{
			result.withError("Server_Msg_Sms_Error_Send", "发送短消息失败,原因:" + smsSucc.getErrMsg());
			logger.info("给用户[{}]发送短消息失败，原因：[{}]", phone, smsSucc.getErrMsg());
		}
		
		return result;
	}

	@Override
	public ModelResult<Boolean> useAuthCode(String phone, String authCode) {
		ModelResult<Boolean> result = new ModelResult<Boolean>();
		
		MsgSmsEntity sms = msgSmsManager.queryAuthCode(phone, authCode);
		if(null == sms){
			logger.info("手机[{}]的验证码[{}]不存在", phone, authCode);
			return result.withError("Server_Msg_Sms_Error_None", "验证码不存在");
		}
		
		if(sms.getSmsStatus() != 0){
			logger.info("手机[{}]的验证码[{}]已使用", phone, authCode);
			return result.withError("Server_Msg_Sms_Error_None", "验证码已使用");
		}
		
		boolean flag = msgSmsManager.updateAuthCodeStatus(phone, authCode, (byte)1);
		if(flag){
			result.withModel(true);
			logger.debug("手机[{}]使用验证码[{}]成功", phone, authCode);
		} else{
			logger.info("手机[{}]使用验证码[{}]失败", phone, authCode);
			result.withError("Server_Msg_Sms_Error_Use_Failure", "验证码使用失败");
		}
		return result;
	}

	@Override
	public ModelResult<PageResult<Object[]>> page(MsgSmsQueryVO vo) {
		ModelResult<PageResult<Object[]>> result = new ModelResult<PageResult<Object[]>>();
		try {
			result.setModel(msgSmsManager.page(vo));
		} catch (Exception e) {
			e.printStackTrace();
			result.withError("分页查询短信列表：", e.getMessage());
		}
		return result;
	}
	
}
